package cn.wmw.xyy.mq.consumer;

import cn.wmw.xyy.bo.CourseOrderPayBo;
import cn.wmw.xyy.domain.PayOrder;
import cn.wmw.xyy.exception.GlobalException;
import cn.wmw.xyy.exception.GlobalExceptionEnum;
import cn.wmw.xyy.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;


@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-order-pay-consumer-group",
        topic = "course-order-pay-topic",
        selectorExpression = "course-order-pay-tag"
)
public class CourseOrderPayComsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;
    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        if (body.length == 0){
            log.error("支付消费异常！！！消息为空！！！");
            throw new GlobalException(GlobalExceptionEnum.ERROR);
        }
        CourseOrderPayBo courseOrderPayBo = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayBo.class);
        // 2.业务校验
        String orderNo = courseOrderPayBo.getOrderNo();
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        if (payOrder != null){
            log.info("支付消费异常，订单已存在，订单号为：" + orderNo);
            return;
        }
        payOrder = new PayOrder();
        payOrder.setAmount(courseOrderPayBo.getTotalAmount());
        payOrder.setOrderNo(orderNo);
        payOrder.setPayType(courseOrderPayBo.getPayType());
        payOrder.setSubject(courseOrderPayBo.getTitle());
        payOrder.setUserId(courseOrderPayBo.getUserId());
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.WAIT_PAY);
        // 保存支付单
        payOrderService.insert(payOrder);
    }
}
